<template>
  <div class="imageloader-container">
    <img :src="placeholder" class="img-placeholder" v-if="!allReady" />
    <img
      :src="src"
      class="img-origin"
      :style="{
        opacity: opacityNum,
        transition: `opacity ${duration}ms ease-in-out`,
      }"
      @load="handlerLoaded"
    />
  </div>
</template>

<script>
export default {
  name: "ImageLoader",
  props: {
    src: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
      required: true,
    },
    duration: {
      type: Number,
      default: 500,
    },
  },
  data() {
    return {
      originalLoaded: false,
      allReady: false,
    };
  },
  methods: {
    handlerLoaded() {
      this.originalLoaded = true;
      setTimeout(() => {
        this.allReady = true;
        this.$emit("loaded");
      }, this.duration);
    },
  },
  computed: {
    opacityNum() {
      return this.originalLoaded ? 1 : 0;
    },
  },
};
</script>

<style scoped lang="less">
.imageloader-container {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
  img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .img-origin {
    opacity: 0;
  }
  .img-placeholder {
    filter: blur(2vw);
  }
}
</style>
